import { tickersApi } from '@/api';
import styles from './biHeader.module.less';
import { useEffect, useState } from 'react';
import { useInterval } from 'ahooks';
import { useSetAtom } from 'jotai';
import { coinAtom } from '@/stores';
import { Popover } from 'antd';
import ContractList from './ContractList';
import { countUsdtNum, formatNum, formatNumUnit } from '@/utils';
import { lunXunTime } from '@/utils/helper';

export default function BiHeader({ contract }: any) {
  const setCoin = useSetAtom(coinAtom);
  const [biInfos, setBiInfos] = useState<any>([]);
  const [data, setData] = useState<any>();
  const [open, setOpen] = useState(false);
  const [contractList, setContractList] = useState<any>(null);

  useEffect(() => {
    if (contract) {
      getContractTickers();
      setTimeout(() => {
        getAllContractTickers();
      }, 1000);
    }
  }, [contract]);

  useInterval(() => {
    getContractTickers();
  }, lunXunTime);

  // 合约行情-单个
  async function getContractTickers() {
    const val: any = (await tickersApi({ contract }))?.data;
    const res: any = val?.[0];
    if (res?.contract) {
      res.contract = res.contract;
      res.contractNew = res.contract.replace('_', '');
      setCoin(res);
      setData(res);
      const _biInfos = [
        { name: '标记价格', val: formatNum(res?.mark_price, 1) },
        { name: '指数价格', val: formatNum(res?.index_price, 1) },
        { name: '24小时最高价', val: formatNum(res?.high_24h, 1) },
        { name: '24小时最低价', val: formatNum(res?.low_24h, 1) },
        { name: '24H交易额(USDT)', val: formatNumUnit(res?.volume_24h_settle) },
        {
          name: '持仓量(USDT)',
          val: formatNumUnit(countUsdtNum(res?.last, res?.total_size, res?.quanto_multiplier)),
        },
        { name: '资金费率', val: `${(res?.funding_rate * 100).toFixed(4)}%` },
      ];
      setBiInfos(_biInfos);
    }
  }

  // 合约行情-所有
  async function getAllContractTickers() {
    const val: any = (await tickersApi())?.data;
    // console.log('val: 合约行情-所有', val);
    setContractList(val);
  }

  return (
    <div className={`${styles.biHeaderWrap} flex bgfff`}>
      <div className={`${styles.curbi} flex`}>
        <Popover
          content={<ContractList contractList={contractList} />}
          open={open}
          trigger={['hover', 'click']}
          onOpenChange={(e) => setOpen(e)}
        >
          <div className={`${styles.info}`}>
            <div className={`${styles.tit}`}>{data?.contractNew}</div>
            <div className={`${styles.desc}`}>永续</div>
          </div>
        </Popover>
      </div>
      <div className={`${styles.pricew}`}>
        <div
          className={`${styles.ttop} ${data?.change_percentage > 0 ? 'color-red' : 'color-green'}`}
        >
          {data?.last && formatNum(data?.last, 1)}
        </div>
      </div>
      <div className={`${styles.tlist}`}>
        {data?.change_percentage && (
          <div className={`${styles.titem}`}>
            <div className={`${styles.name}`}>涨跌幅</div>
            <div
              className={`${styles.val} ${data?.change_percentage > 0 ? 'color-red' : 'color-green'}`}
            >
              {data?.change_percentage > 0 ? '+' : ''}
              {formatNum(data?.change_percentage, 2)}%
            </div>
          </div>
        )}

        {biInfos &&
          biInfos.map((item: any, index: number) => (
            <div className={`${styles.titem}`} key={index}>
              <div className={`${styles.name}`}>{item?.name}</div>
              <div className={`${styles.val} `}>{item?.val}</div>
            </div>
          ))}
      </div>
      <div className={`${styles.xxx}`}></div>
      <div className={`${styles.xxx}`}></div>
    </div>
  );
}
